﻿using HookupAppForm.Draw.Models;
using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HookupAppForm.Draw
{
    /// <summary>
    /// UC_DrawEdit.xaml 的交互逻辑
    /// </summary>
    public partial class UC_DrawShow : UserControl, INotifyPropertyChanged
    {
        public UC_DrawShow()
        {
            InitializeComponent();
            DataContext = this;
            Loaded += UC_DrawEdit_Loaded;
        }

        #region 变量 + 绑定属性
        private APIClient client;
        private string bindtypeps = @"
接点:接点位置
接点:接点类型
接点:接点管径
接点:设计流量负荷
接点:平均流量
接点:操作流量负荷
接点:最小流量

机台:机台位置（X、Y）
机台:机台接口需求
机台:机台尺寸大小
 
区域:区域位置（XY）
区域:区域大小
 
管道:管道位置
管道:流量大小
管道:管道类型

";
        private Dictionary<string, List<string>> bindTypePsDict = new Dictionary<string, List<string>>();
        private SolidColorBrush brush_line = new SolidColorBrush(Color.FromRgb(128, 128, 128));
        private SolidColorBrush brush_bg = new SolidColorBrush(Color.FromRgb(33, 40, 48));
        private bool showMeshBg = true;
        private bool showMeshRule = true;

        private Point pt_mousedown = new Point();
        private DrawCommand CurrDrawCommand = DrawCommand.缩放;
        private GridExt MenuItemGrid = null;
        private FrameworkElement curr_draw_shape = null;
        private Point curr_draw_ptdown = new Point();
        private TextBlock curr_draw_text = null;
        private Point curr_draw_ptup = new Point();
        private bool curr_draw_going = false;
        private List<FrameworkElement> shadow_todrags = new List<FrameworkElement>();
        private bool dragGoing = false;

        private Border bd_slt_area = null;
        private Point pt_select_mousedown = new Point();
        private Point pt_select_mouseup = new Point();
        private string imgtmp = AppDomain.CurrentDomain.BaseDirectory + "tmp.png";

        private Brush bs_red_opt10 = new SolidColorBrush(Color.FromArgb(1, 255, 0, 0));

        private List<CanvasExt> lst_container_jiedian = new List<CanvasExt>();
        private List<DrawEleInfo> drawEleListInUI = new List<DrawEleInfo>();

        //相对于背景图的位置
        internal int mouseMoveX_Draw = 0;
        internal int mouseMoveY_Draw = 0;
        internal int mouseDownX_Draw = 0;
        internal int mouseDownY_Draw = 0;

        internal Action refreshDataJiedianAction = null;
        internal Action refreshDataQuyuAction = null;
        internal Action refreshDataGuandaoAction = null;
        internal Action refreshDataAction = null;
        internal Action refreshDrawAction = null;
        string ln_hor_split_arr = "";
        string ln_hor_split_arr_sign = "";
        string ln_ver_split_arr = "";
        string ln_ver_split_arr_sign = "";

        internal double[] split_arr_col = new double[0];
        internal double[] split_arr_row = new double[0];
        private string[] split_arr_sign_col = new string[0];
        private string[] split_arr_sign_row = new string[0];
        internal double colWidthItemAvg = 100;
        internal double rowHeightItemAvg = 100;

        private List<CanvasExt> lst_searched_jiedian = new List<CanvasExt>();
        private List<CanvasExt> lst_searched_jiedian_novalid = new List<CanvasExt>();
        private Brush bs_filter = new SolidColorBrush(Color.FromArgb(127, 0, 255, 0));
        private Brush bs_filter_not = new SolidColorBrush(Color.FromArgb(127, 255, 0, 0));



        internal double drawEdge_hor
        {
            get { return colWidthItemAvg * 2; }
        }
        internal double drawEdge_ver
        {
            get { return rowHeightItemAvg * 2; }
        }

        public ObservableCollection<DrawEleInfo> EleList
        {
            get
            {
                if (CurrDrawInfo.EleList == null) CurrDrawInfo.EleList = new ObservableCollection<DrawEleInfo>();
                return CurrDrawInfo.EleList;
            }
            set
            {
                CurrDrawInfo.EleList = value;
                cc("EleList");
            }
        }
        private DrawEleInfo _EleSelected;
        public DrawEleInfo EleSelected
        {
            get
            {
                return _EleSelected;
            }
            set
            {
                _EleSelected = value;
                cc("EleSelected");

                if (EleList != null) foreach (var v in EleList) v.IsSlt = false;
                if (value != null) value.IsSlt = true;
            }
        }
        public double bg_ln_thickness
        {
            get
            {
                var normalLen = 1;
                return Math.Max(normalLen, normalLen / ImgScaleX);
            }
        }
        public double EllScaleTimes
        {
            get
            {
                var normalLen = 1;
                return Math.Max(normalLen, normalLen / ImgScaleX);
            }
        }

        /// <summary>
        /// Y取值反
        /// </summary>
        public double EllScaleTimesYFlip
        {
            get
            {
                var normalLen = 1;
                return -Math.Max(normalLen, normalLen / ImgScaleX);
            }
        }
        public double DesFontSizeWithScale
        {
            get
            {
                var normalLen = 12;
                return Math.Max(1, normalLen / ImgScaleX);
            }
        }
        public Thickness MarginBottomWithScale
        {
            get
            {
                var normalLen = -5;
                return new Thickness(0, 0, 0, normalLen / ImgScaleX);
            }
        }


        private CustomDrawInfo _CurrDrawInfo = new CustomDrawInfo();
        public CustomDrawInfo CurrDrawInfo
        {
            get
            {
                return _CurrDrawInfo;
            }
            set
            {
                _CurrDrawInfo = value;
                cc("CurrDrawInfo");
            }
        }


        #endregion

        #region 事件

        /// <summary>
        /// 页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UC_DrawEdit_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(delegate
            {
                Thread.Sleep(200);
                Dispatcher.Invoke(delegate
                {
                    client = FormMain.Instance.client;

                    //列表-接点类型 
                    string url = string.Format("api/services/app/HKP_Category/GetList?layout={0}&parentId={1}", "BaseType", 0);
                    var result = client.Get(url);
                    ItemsDto<HKP_CategoryDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_CategoryDto>>(result);
                    comboBoxM.DisplayMemberPath = "CateName";
                    comboBoxM.SelectedValuePath = "Id";
                    comboBoxM.ItemsSource = res?.result?.items;

                    loadBg();
                    LoadBindType();

                });
            });
        }

        /// <summary>
        /// 切换绑定数据类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CbBindType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0) return;

            var newname = e.AddedItems[0].ToString();
            LoadBindProperties(newname);
        }

        /// <summary>
        /// 点击按钮-保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_saveshape_click(object sender, RoutedEventArgs e)
        {
        }

        /// <summary>
        /// 鼠标点击画布
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_mousedown(object sender, MouseButtonEventArgs e)
        {
            //此时鼠标相对于画布的位置
            var pt = e.GetPosition(cvDrawBg);
            mouseDownX_Draw = (int)Math.Round(pt.X - colWidthItemAvg * 2);
            mouseDownY_Draw = (int)Math.Round(pt.Y - rowHeightItemAvg * 2);


            if (CurrDrawCommand == DrawCommand.无) return;
            if (CurrDrawCommand == DrawCommand.拖动) return;
            if (CurrDrawCommand == DrawCommand.复制) return;
            if (CurrDrawCommand == DrawCommand.删除) return;


            if (curr_draw_going)
            {
                draw_end(sender, e);
            }
            else
            {

                draw_start(sender, e);

            }
        }

        /// <summary>
        /// 画图开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void draw_start(object sender, MouseButtonEventArgs e)
        {
            if (CurrDrawCommand == DrawCommand.无) return;
            if (CurrDrawCommand == DrawCommand.删除) return;
            if (CurrDrawCommand == DrawCommand.复制) return;
            if (CurrDrawCommand == DrawCommand.拖动) return;
            if (CurrDrawCommand == DrawCommand.缩放) return;
            curr_draw_going = true;
            cvDrawMain.Cursor = Cursors.Cross;
            curr_draw_ptdown = e.GetPosition(cvDrawMain);

            //新增绑定对象
            EleSelected = new DrawEleInfo();
            EleSelected.DrawCommand = CurrDrawCommand;
            //使用上一个绘制图形的线条颜色属性
            if (EleList.Any(a => a.DrawCommand == CurrDrawCommand))
            {
                var elelast = EleList.Last(a => a.DrawCommand == CurrDrawCommand);
                EleSelected = elelast.Clone() as DrawEleInfo;
            }

            EleSelected.uid = Guid.NewGuid().ToString();
            EleSelected.LocX = curr_draw_ptdown.X;
            EleSelected.LocY = curr_draw_ptdown.Y;
            EleSelected.LocX2 = curr_draw_ptdown.X;
            EleSelected.LocY2 = curr_draw_ptdown.Y;
            EleList.Add(EleSelected);
            ResetRowHeader();
            foreach (var ele in EleList) ele.IsSlt = false;
            EleSelected.IsSlt = true;

            doAddDrawEleControl(EleSelected);
        }


        /// <summary>
        /// 画图中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_mousemove(object sender, MouseEventArgs e)
        {
            var pt = e.GetPosition(cvDrawBg);

            //去掉边缘距离
            mouseMoveX_Draw = (int)Math.Round(pt.X - drawEdge_hor);
            //左下角为 0 0 
            mouseMoveY_Draw = (int)(Math.Round(pt.Y - drawEdge_ver));
            DrawBgMouseMoveAction?.Invoke(mouseMoveX_Draw, mouseMoveY_Draw);



            if (CurrDrawCommand == DrawCommand.无) return;
            if (!curr_draw_going) return;
            var curr_draw_new = e.GetPosition(cvDrawMain);

            switch (CurrDrawCommand)
            {
                case DrawCommand.直线:
                case DrawCommand.矩形:
                case DrawCommand.圆形:
                    EleSelected.LocX2 = curr_draw_new.X;
                    EleSelected.LocY2 = curr_draw_new.Y;
                    break;
                case DrawCommand.曲线:
                    break;
                case DrawCommand.文字:
                    break;
                case DrawCommand.拖动:
                    break;
                case DrawCommand.缩放:
                    break;
                case DrawCommand.复制:
                    break;
                case DrawCommand.删除:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 画图结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void draw_end(object sender, MouseButtonEventArgs e)
        {
            if (CurrDrawCommand == DrawCommand.无) return;

            curr_draw_going = false;
        }


        /// <summary>
        /// 开始拖动，仅仅针对于已选中元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Shape_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;

            var eletmp = sender as FrameworkElement;
            var eletmpInfo = eletmp.DataContext as DrawEleInfo;
            if (!eletmpInfo.IsSlt) return;

            shadow_todrags.Clear();
            foreach (FrameworkElement fe in cvDrawMain.Children)
            {
                var feinfo = (fe.DataContext as DrawEleInfo);
                if (feinfo == null) continue;
                if (!feinfo.IsSlt) continue;
                shadow_todrags.Add(fe);
            }
            if (CurrDrawCommand == DrawCommand.拖动)
            {
                pt_mousedown = e.GetPosition(cvDrawMain);
                //loc_ele_beforeMove = new Point(Canvas.GetLeft(shadow_todrag), Canvas.GetTop(shadow_todrag));
                dragGoing = true;
                cvDrawMask.Visibility = Visibility.Visible;
            }
            else cvDrawMask.Visibility = Visibility.Collapsed;

        }

        /// <summary>
        /// 拖动中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawMask_MouseMove(object sender, MouseEventArgs e)
        {
            if (!dragGoing) return;
            if (CurrDrawCommand == DrawCommand.无) return;
        }

        /// <summary>
        /// 停止拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawMask_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!dragGoing) return;
            if (CurrDrawCommand == DrawCommand.无) return;
        }

        /// <summary>
        /// 鼠标悬浮元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void New_line_MouseMove(object sender, MouseEventArgs e)
        {
            var ln = sender as FrameworkElement;
            if (ln.DataContext as DrawEleInfo is null) return;
            (ln.DataContext as DrawEleInfo).IsMouseOver = true;

            //if (ln.Tag != null && ln.Tag.ToString() == "ismouseover") return;

            //ln.Tag = "ismouseover";
            //if (ln is Shape) (ln as Shape).Stroke = bs_red_mouseover;
            //else if (ln is Border) (ln as Border).BorderBrush = bs_red_mouseover;
        }

        /// <summary>
        /// 鼠标悬浮元素结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void New_line_MouseLeave(object sender, MouseEventArgs e)
        {
            var ln = sender as FrameworkElement;
            if (ln.DataContext as DrawEleInfo is null) return;
            (ln.DataContext as DrawEleInfo).IsMouseOver = false;
        }

        /// <summary>
        /// 清空画布
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_cleardraw_click(object sender, RoutedEventArgs e)
        {
            cvDrawMain.Children.Clear();
            if (EleList.Any()) EleList.Clear();
            EleSelected = null;
            drawEleListInUI.Clear();
        }

        /// <summary>
        /// 列表中删除指定元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_del_item(object sender, RoutedEventArgs e)
        {
            var eleinfo = (sender as Button).DataContext as DrawEleInfo;

        }

        /// <summary>
        /// 画布批量选择-鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawSelect_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;
            pt_select_mousedown = e.GetPosition(cvDrawSelect);

            //全选区域，选择区域内元素，支持批量选择
            bd_slt_area = new Border() { Width = 10, Height = 10 };
            bd_slt_area.BorderBrush = Brushes.White;
            bd_slt_area.Background = Brushes.White;
            bd_slt_area.Opacity = 0.3;
            Canvas.SetLeft(bd_slt_area, pt_select_mousedown.X);
            Canvas.SetTop(bd_slt_area, pt_select_mousedown.Y);
            cvDrawMain.Children.Add(bd_slt_area);

        }

        /// <summary>
        /// 画布批量选择-鼠标按下移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawSelect_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;
            if (bd_slt_area == null) return;

            pt_select_mouseup = e.GetPosition(cvDrawSelect);

            var width = Math.Max(10, pt_select_mouseup.X - pt_select_mousedown.X);
            var height = Math.Max(10, pt_select_mouseup.Y - pt_select_mousedown.Y);
            bd_slt_area.Width = width;
            bd_slt_area.Height = height;
        }

        /// <summary>
        /// 画布批量选择-鼠标抬起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawSelect_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (bd_slt_area == null) return;

            //移除全选标记
            cvDrawMain.Children.Remove(bd_slt_area);

            //当前全选区域
            var rt_slt = new Rect(Canvas.GetLeft(bd_slt_area),
                Canvas.GetTop(bd_slt_area),
                bd_slt_area.Width,
                bd_slt_area.Height
                );

            //选择该区域的元素
            List<FrameworkElement> fe_slt_lst = new List<FrameworkElement>();
            foreach (var fe in cvDrawMain.Children.Cast<FrameworkElement>().Where(a => a != bd_slt_area))
            {
                var eleinfo = (fe as FrameworkElement).DataContext as DrawEleInfo;
                var rt = new Rect(eleinfo.LocX, eleinfo.LocY, eleinfo.SizeWidth, eleinfo.SizeHeight);
                if (rt.IntersectsWith(rt_slt)) fe_slt_lst.Add(fe);
            }

            //仅仅显示第一个的相关属性信息
            if (fe_slt_lst.Any()) EleSelected = (fe_slt_lst.First().DataContext as DrawEleInfo);

            //设置为选中
            foreach (var ele in EleList) ele.IsSlt = false;
            foreach (var fe in fe_slt_lst) (fe.DataContext as DrawEleInfo).IsSlt = true;

            bd_slt_area = null;
        }


        /// <summary>
        /// 设置边框线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var scb = Brushes.Black;
            if (!ColorSelector(out scb)) return;


            if (EleSelected == null) return;
            EleSelected.Stroke = scb;
        }
        /// <summary>
        /// 设置填充色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Border_MouseLeftButtonDown_fill(object sender, MouseButtonEventArgs e)
        {
            var scb = Brushes.Black;
            if (!ColorSelector(out scb)) return;

            if (EleSelected == null) return;
            EleSelected.Fill = scb;
        }

        /// <summary>
        /// 添加区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mi_add_quyu_click(object sender, RoutedEventArgs e)
        {
            FormBlock form = new FormBlock(null, client, DrawingCacheInfo.text_building, DrawingCacheInfo.text_floor);
            Task.Run(delegate
            {
                Thread.Sleep(500);
                Dispatcher.Invoke(delegate
                {
                    try
                    {
                        form.SetLoc(mouseDownX_Draw, mouseDownY_Draw);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("该位置不可添加区域！");
                    }
                });
            });
            form.ShowDialog();


            refreshDataQuyuAction?.Invoke();
        }

        /// <summary>
        /// 添加接点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mi_add_jiedian_click(object sender, RoutedEventArgs e)
        {
            FormTakeOff form = new FormTakeOff(null, client);
            Task.Run(delegate
            {
                Thread.Sleep(500);
                Dispatcher.Invoke(delegate
                {
                    try
                    {
                        form.SetLoc(mouseDownX_Draw, mouseDownY_Draw);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("该位置不可添加接点！");
                    }

                });
            });
            form.ShowDialog();


            refreshDataJiedianAction?.Invoke();
        }

        /// <summary>
        /// 添加管道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mi_add_guandao_click(object sender, RoutedEventArgs e)
        {
            FormSubmain form = new FormSubmain(null, client);
            form.ShowDialog();

            refreshDataGuandaoAction?.Invoke();
        }

        /// <summary>
        /// 筛选接点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_filter_jiedian(object sender, RoutedEventArgs e)
        {
            try
            {
                var p_outtype = comboBoxM.Text;
                //if (string.IsNullOrWhiteSpace(p_outtype))
                //{
                //    MessageBox.Show("请录入有效的筛选条件！");
                //    return;
                //}
                var used = cbJiedianUsed.IsChecked == true;
                //var ids_match = ParentLayout.jiedian_lst_curr.Where(a => a.OutType == p_outtype && a.Used == used).Select(a => a.Id).ToList();
                var ids_match = ParentLayout.jiedian_lst_curr.Where(a => a.Used == used).Select(a => a.Id).ToList();
                var oklist = lst_container_jiedian.Where(a => a.Data_Jiedian != null && ids_match.Contains(a.Data_Jiedian.Id)).ToList();

                lst_searched_jiedian = oklist;
                lst_searched_jiedian_novalid = lst_container_jiedian.Except(oklist).ToList();

                foreach (var cv in lst_searched_jiedian)
                {
                    var da = cv.Data_Jiedian as HKP_TakeoffDto;
                    if (da == null) continue;

                    cv.Background = bs_filter;
                }
                foreach (var cv in lst_searched_jiedian_novalid)
                {
                    var da = cv.Data_Jiedian as HKP_TakeoffDto;
                    if (da == null) continue;

                    cv.Background = bs_filter_not;
                }
                if (oklist.Count == 0)
                {
                    MessageBox.Show("没有搜索到相关的数据！");
                    return;
                }
            }
            catch (Exception ee)
            {
            }
        }

        private void btn_filter_jiedian_del(object sender, RoutedEventArgs e)
        {
            if (lst_searched_jiedian != null)
            {
                foreach (var cv in lst_searched_jiedian)
                {
                    var da = cv.Data_Jiedian as HKP_TakeoffDto;
                    if (da == null) continue;

                    cv.Background = Brushes.Transparent;
                }
            }
            if (lst_searched_jiedian_novalid != null)
            {
                foreach (var cv in lst_searched_jiedian_novalid)
                {
                    var da = cv.Data_Jiedian as HKP_TakeoffDto;
                    if (da == null) continue;

                    cv.Background = Brushes.Transparent;
                }
            }
            if ((lst_searched_jiedian == null || lst_searched_jiedian.Count == 0)
                && (lst_searched_jiedian_novalid == null || lst_searched_jiedian_novalid.Count == 0))
            {
                MessageBox.Show("没有需要清除的数据！");
                return;
            }
            lst_searched_jiedian = null;
            lst_searched_jiedian_novalid = null;
        }

        private void mi_add_jiedian_click_root(object sender, RoutedEventArgs e)
        {
            FormTakeOff form = new FormTakeOff(null, client);
            Task.Run(delegate
            {
                Thread.Sleep(500);
                Dispatcher.Invoke(delegate
                {
                    try
                    {
                        form.SetLoc(mouseDownX_Draw, mouseDownY_Draw);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("该位置不可添加接点！");
                    }
                });
            });
            form.ShowDialog();


            refreshDataJiedianAction?.Invoke();
        }

        private void mi_add_jiedian_click_guandao(object sender, RoutedEventArgs e)
        {
            FormSubmain form = new FormSubmain(null, client);
            Task.Run(delegate
            {
                Thread.Sleep(500);
                Dispatcher.Invoke(delegate
                {
                    try
                    {
                        form.SetLoc(mouseDownX_Draw, mouseDownY_Draw);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("该位置不可添加管道！");
                    }
                });
            });
            form.ShowDialog();



            refreshDataGuandaoAction?.Invoke();

        }


        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        /// <summary>
        /// 导出图形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_exportshape_click(object sender, RoutedEventArgs e)
        {
            if (EleList == null || EleList.Count == 0)
            {
                MessageBox.Show("没有需要导出的内容！");
                return;
            }
            try
            {
                var shapeExport = CurrDrawInfo;
                var jstr = Newtonsoft.Json.JsonConvert.SerializeObject(shapeExport);
                byte[] b = System.Text.Encoding.Default.GetBytes(jstr);
                var bstr = Convert.ToBase64String(b);
                var sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.FileName = "导出图形_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".HDCDRAW";
                if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

                System.IO.File.WriteAllText(sfd.FileName, bstr);
                MessageBox.Show("导出成功！");
            }
            catch (Exception)
            {
                MessageBox.Show("导出图形发生了异常，请稍后重试！");
            }
        }

        /// <summary>
        /// 导入图形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_importshape_click(object sender, RoutedEventArgs e)
        {
            try
            {
                var ofd = new System.Windows.Forms.OpenFileDialog();
                ofd.Filter = "*.HDCDRAW|*.HDCDRAW";
                ofd.Multiselect = false;
                if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

                //清除现有的
                EleList.Clear();
                cvDrawMain.Children.Clear();
                EleSelected = null;
                drawEleListInUI.Clear();



                var bstr = System.IO.File.ReadAllText(ofd.FileName);
                byte[] c = Convert.FromBase64String(bstr);
                var jstr = System.Text.Encoding.Default.GetString(c);
                var shapeExport = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomDrawInfo>(jstr);
                CurrDrawInfo = (CustomDrawInfo)shapeExport;
                EleList = (ObservableCollection<DrawEleInfo>)shapeExport.EleList;

                foreach (var ele in EleList) doAddDrawEleControl(ele);

                MessageBox.Show("导入成功！");

            }
            catch (Exception)
            {
                MessageBox.Show("导入图形发生了异常，请导入有效的图形文件！");
            }
        }

        /// <summary>
        /// 显示背景
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

            showMeshBg = true;
            loadBg();
        }
        /// <summary>
        /// 隐藏背景
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {

            showMeshBg = false;
            loadBg();
        }

        /// <summary>
        /// 显示刻度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            showMeshRule = true;
            loadBg();
        }

        /// <summary>
        /// 隐藏刻度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Unchecked_1(object sender, RoutedEventArgs e)
        {
            showMeshRule = false;
            loadBg();
        }

        /// <summary>
        /// 编辑轴线-横线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mi_lineHor_click(object sender, RoutedEventArgs e)
        {
            var win = new UC_LineEdit(ln_hor_split_arr, ln_hor_split_arr_sign);
            win.ShowDialog();
            ln_hor_split_arr = win.str_split;
            ln_hor_split_arr_sign = win.str_sign;
            if (!win.saveOK) return;

            //更新布局
            loadBg();
            SaveBgDraw();
        }
        private void SaveBgDraw()
        {
            if (DrawingCacheInfo.DrawDetail == null)
                DrawingCacheInfo.DrawDetail = new FDInfo();

            DrawingCacheInfo.DrawDetail.ln_hor_split_arr = ln_hor_split_arr;
            DrawingCacheInfo.DrawDetail.ln_hor_split_arr_sign = ln_hor_split_arr_sign;
            DrawingCacheInfo.DrawDetail.ln_ver_split_arr = ln_ver_split_arr;
            DrawingCacheInfo.DrawDetail.ln_ver_split_arr_sign = ln_ver_split_arr_sign;

            Task.Run(() =>
            {
                if (DrawingCacheInfo.id <= 0) LocalDataHelper.AddFloorDrawInfo(DrawingCacheInfo);
                else LocalDataHelper.UpdateFloorDrawInfo(DrawingCacheInfo);
            });

        }
        /// <summary>
        /// 编辑轴线-竖线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mi_lineVer_click(object sender, RoutedEventArgs e)
        {
            var win = new UC_LineEdit(ln_ver_split_arr, ln_ver_split_arr_sign);
            win.ShowDialog();
            ln_ver_split_arr = win.str_split;
            ln_ver_split_arr_sign = win.str_sign;
            if (!win.saveOK) return;

            //更新布局
            loadBg();
            SaveBgDraw();
        }

        private void btn_refresh_click(object sender, RoutedEventArgs e)
        {
            refreshDrawAction?.Invoke();
        }

        private void btn_refreshdata_click(object sender, RoutedEventArgs e)
        {
            refreshDataAction?.Invoke();
            refreshDrawAction?.Invoke();
        }



        #endregion

        #region 方法


        private void LoadBindProperties(string btype)
        {
            var lst1 = bindTypePsDict.ContainsKey(btype) ? bindTypePsDict[btype] : new List<string>();
            lst1.Insert(0, "请选择");
        }

        private void LoadBindType()
        {
            //绑定类型
            foreach (var str in bindtypeps.Split("\r\n").Where(a => !string.IsNullOrWhiteSpace(a)))
            {
                var arr2 = str.Split(':').Where(a => !string.IsNullOrWhiteSpace(a)).ToArray();
                if (arr2.Length != 2) continue;

                var type = arr2[0];
                var prop = arr2[1];
                if (!bindTypePsDict.ContainsKey(type))
                    bindTypePsDict.Add(type, new List<string>());

                bindTypePsDict[type].Add(prop);
            }
            var ls = bindTypePsDict.Keys.ToList();
            ls.Insert(0, "请选择");
        }

        private System.Drawing.Bitmap GenPreviewImg()
        {
            var ImgScaleX_old = ImgScaleX;
            var ImgScaleY_old = ImgScaleY;
            var ImgMoveX_old = ImgMoveX;
            var ImgMoveY_old = ImgMoveY;

            ImgScaleX = 1;
            ImgScaleY = 1;
            ImgMoveX = 0;
            ImgMoveY = 0;


            System.Drawing.Bitmap rstmap = null;

            try
            {

                if (EleList == null || EleList.Count == 0) return rstmap;

                //生成预览图形 
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)cvDrawMain.ActualWidth, (int)cvDrawMain.ActualHeight, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(cvDrawMain);
                string file = imgtmp;
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                using (Stream stm = File.Create(file)) encoder.Save(stm);

                var x1 = (int)EleList.Min(a => a.LocX);
                var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                var y1 = (int)EleList.Min(a => a.LocY);
                var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                var rtvalid = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                var img = System.Drawing.Image.FromFile(file) as System.Drawing.Bitmap;
                rstmap = new System.Drawing.Bitmap(rtvalid.Width, rtvalid.Height);
                var g = System.Drawing.Graphics.FromImage(rstmap);
                g.Clear(System.Drawing.Color.Transparent);
                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, rtvalid.Width, rtvalid.Height), rtvalid, System.Drawing.GraphicsUnit.Pixel);
                g.Dispose();
                img.Dispose();
                //mapnew.Save(file);

                return rstmap;
            }
            catch (Exception)
            {
                return rstmap;
            }
            finally
            {

                ImgScaleX = ImgScaleX_old;
                ImgScaleY = ImgScaleY_old;
                ImgMoveX = ImgMoveX_old;
                ImgMoveY = ImgMoveY_old;
            }
        }

        private System.Drawing.Bitmap ResizeMap(System.Drawing.Bitmap map, int resizeWidth)
        {
            var wd = resizeWidth;
            var ht = (int)Math.Round(map.Height / (double)map.Width * resizeWidth);
            return ResizeMap(map, resizeWidth, ht);
        }

        private System.Drawing.Bitmap ResizeMap(System.Drawing.Bitmap map, int resizeWidth, int resizeHeight)
        {
            var wd = resizeWidth;
            var ht = resizeHeight;
            var maprst = new System.Drawing.Bitmap(wd, ht);
            var g = System.Drawing.Graphics.FromImage(maprst);
            g.DrawImage(map, new System.Drawing.Rectangle(0, 0, maprst.Width, maprst.Height), new System.Drawing.RectangleF(0, 0, map.Width, map.Height), System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();
            return maprst;
        }

        /// <summary>
        /// 图形的容器控件
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="wd"></param>
        /// <param name="ht"></param>
        internal CanvasExt doAddDrawEleContainer_Quyu(Rect rt)
        {
            //去掉边缘距离 
            CanvasExt cv = null;
            Dispatcher.Invoke(delegate
            {
                cv = new CanvasExt();
                cv.Background = Brushes.Transparent;
                //cv.Background = bs_red_opt10;
                cv.Width = rt.Width;
                cv.Height = rt.Height;
                Canvas.SetLeft(cv, rt.X);
                Canvas.SetTop(cv, rt.Y);
                cvDrawMain.Children.Add(cv);

            });
            return cv;
        }

        internal CanvasExt doAddDrawEleContainer_Guandao(Rect rt)
        {
            //去掉边缘距离 
            CanvasExt cv = null;
            Dispatcher.Invoke(delegate
            {
                cv = new CanvasExt();
                cv.Background = Brushes.Transparent;
                //cv.Background = bs_red_opt10;
                cv.Width = rt.Width;
                cv.Height = rt.Height;
                Canvas.SetLeft(cv, rt.X);
                Canvas.SetTop(cv, rt.Y);
                cvDrawMain.Children.Add(cv);

            });
            return cv;
        }
 
        internal void doAddDrawEleContainer_Desc_Quyu(CanvasExt cv, string descStr)
        {
            Dispatcher.Invoke(delegate
            {
                //底部区域名称说明
                var bd = new Border() { Width = cv.Width, Height = cv.Height };
                var tb = new TextBlock() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom, Text = descStr, Padding = new Thickness(0, 0, 0, 5), FontSize = 20, FontWeight = FontWeights.Normal, Foreground = Brushes.White, Opacity = 0.8 };
                //tb.RenderTransformOrigin = new Point(0.5, 0.5);
                //tb.RenderTransform = gridmain.FindResource("tfg1") as TransformGroup;
                tb.DataContext = this;
                tb.SetBinding(TextBlock.FontSizeProperty, new Binding() { Path = new PropertyPath("DesFontSizeWithScale"), IsAsync = false });
                bd.Child = tb;
                Canvas.SetLeft(bd, 0);
                Canvas.SetTop(bd, 0);
                cv.Children.Add(bd);
            });
        }
        internal TransformGroup GetYFlipTrans1And1()
        {
          return   gridmain.FindResource("tfg1_textYFlip_loc_1And1") as TransformGroup;
        }
        internal void doAddDrawEleContainer_Desc_Jitai(CanvasExt cv, string descStr)
        {
            Dispatcher.Invoke(delegate
            {
                //底部区域名称说明
                var bd = new Border() { Width = cv.Width, Height = cv.Height };
                var tb = new TextBlock() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top, Text = descStr, Padding = new Thickness(0, 0, 0, 15), FontSize = 12, FontWeight = FontWeights.Normal, Foreground = Brushes.White, Opacity = 0.8, Margin = new Thickness(0, -30, 0, 0) };
                tb.RenderTransformOrigin = new Point(0.5, 0.5);
                tb.RenderTransform = gridmain.FindResource("tfg1_loc") as TransformGroup;
                tb.DataContext = this; 
                bd.Child = tb;
                Canvas.SetLeft(bd, 0);
                Canvas.SetTop(bd, 0);
                cv.ClipToBounds = false;
                cv.Children.Add(bd);
            });
        }

        internal Ellipse doAddDrawEle_JTRound(Rect rt)
        {
            Ellipse bd = null;
            Dispatcher.Invoke(delegate
            {
                //底部区域名称说明
                bd = new Ellipse() { Width = rt.Width, Height = rt.Height, Fill = Brushes.Lime, Opacity = 0.1, RenderTransformOrigin = new Point(0.5, 0.5) };
                //bd.RenderTransformOrigin = new Point(0.5, 0.5);
                //bd.RenderTransform = gridmain.FindResource("tfg1_loc") as TransformGroup;
                bd.DataContext = this;
                Canvas.SetLeft(bd, rt.Left);
                Canvas.SetTop(bd, rt.Top);
                cvDrawMain.Children.Add(bd);
            });
            return bd;
        }

        internal CanvasExt doAddDrawEleContainer_Jiedian(Canvas canvasParent, Rect rt)
        {
            //去掉边缘距离 
            CanvasExt cv = null;
            Dispatcher.Invoke(delegate
            {
                cv = new CanvasExt();
                cv.ClipToBounds = false;
                cv.Background = Brushes.Transparent;
                //cv.Background = bs_red_opt10;
                cv.Width = rt.Width;
                cv.Height = rt.Height;
                Canvas.SetLeft(cv, rt.X);
                Canvas.SetTop(cv, rt.Y);
                canvasParent.Children.Add(cv);
            });
            lst_container_jiedian.Add(cv);
            return cv;
        }
        internal CanvasExt doAddBgCanvas(Canvas canvasParent)
        {
            Rect rt = new Rect(0, 0, canvasParent.Width, canvasParent.Height);

            //去掉边缘距离 
            CanvasExt cv = null;
            Dispatcher.Invoke(delegate
            {
                cv = new CanvasExt();
                cv.ClipToBounds = false;
                cv.Background = Brushes.Transparent;
                //cv.Background = bs_red_opt10;
                cv.Width = rt.Width;
                cv.Height = rt.Height;
                Canvas.SetLeft(cv, rt.X);
                Canvas.SetTop(cv, rt.Y);
                canvasParent.Children.Add(cv);
            });
            return cv;
        }
        internal CanvasExt doAddDrawEleContainer_Jiedian(Rect rt)
        {
            //去掉边缘距离 
            CanvasExt cv = null;
            Dispatcher.Invoke(delegate
            {
                cv = new CanvasExt();
                cv.ClipToBounds = false;
                cv.Background = Brushes.Transparent;
                //cv.Background = bs_red_opt10;
                cv.Width = rt.Width;
                cv.Height = rt.Height;
                Canvas.SetLeft(cv, rt.X);
                Canvas.SetTop(cv, rt.Y);
                cvDrawMain.Children.Add(cv);
            });
            lst_container_jiedian.Add(cv);
            return cv;
        }
        internal void doAddDrawEleContainer_Desc_Jiedian(CanvasExt cv, string descStr, int jiedienHeight)
        {
            Dispatcher.Invoke(delegate
            {
                //底部区域名称说明 
                var tb = new TextBlock() { HorizontalAlignment = HorizontalAlignment.Right, Text = descStr, FontSize = jiedienHeight / 3 * 2, Foreground = Brushes.White, Opacity = 0.9 };
                Canvas.SetRight(tb, colWidthItemAvg * 0.01);
                Canvas.SetTop(tb, jiedienHeight / 6);
                cv.Children.Add(tb);
            });
        }

        private void BindThicknessScale(System.Windows.Shapes.Shape shape, DrawEleInfo eleinfo)
        {
            shape.DataContext = eleinfo;
            shape.SetBinding(Line.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeThicknessScaleResult"), IsAsync = false, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
        }
        private void BindThicknessScale(System.Windows.Controls.Border shape, DrawEleInfo eleinfo)
        {
            shape.DataContext = eleinfo;
            shape.SetBinding(System.Windows.Controls.Border.BorderThicknessProperty, new Binding() { Path = new PropertyPath("StrokeThicknessScaleResult"), IsAsync = false, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
        }


        private void ResetStroke()
        {
            try
            {
                foreach (var eleinfo in drawEleListInUI) eleinfo.StrokeThicknessScale = ImgScaleX;
                //if (drawEleListInUI.Count == 0) return;

                //drawEleListInUI.First().Dispatcher.Invoke(delegate
                //{
                //foreach (var item in drawEleListInUI)
                //{
                //    var eleinfo = item.DataContext as DrawEleInfo;
                //    var thickness = eleinfo.StrokeThickness / ImgScaleX;

                //    if (item is System.Windows.Shapes.Shape)
                //    {
                //        (item as System.Windows.Shapes.Shape).StrokeThickness = thickness;
                //    }
                //    else if (item is System.Windows.Controls.Border)
                //    {
                //        (item as System.Windows.Controls.Border).BorderThickness = new Thickness(thickness);
                //    }
                //}

                //    foreach (var item in drawEleListInUI)
                //    {
                //        var eleinfo = item.DataContext as DrawEleInfo;
                //        eleinfo.StrokeThicknessScale = ImgScaleX;


                //        var thickness = eleinfo.StrokeThickness / ImgScaleX;

                //        if (item is System.Windows.Shapes.Shape)
                //        {
                //            (item as System.Windows.Shapes.Shape).StrokeThickness = thickness;
                //        }
                //        else if (item is System.Windows.Controls.Border)
                //        {
                //            (item as System.Windows.Controls.Border).BorderThickness = new Thickness(thickness);
                //        }
                //    }

                //});
            }
            catch (Exception ee)
            {

            }
        }

        /// <summary>
        /// 根据上下文添加一个控件
        /// </summary>
        /// <param name="EleSelected"></param>
        internal void doAddDrawEleControl(DrawEleInfo EleSelected, Canvas cvContainer = null)
        {
            Dispatcher.Invoke(delegate
            {
                if (cvContainer == null) cvContainer = cvDrawMain;
                var thickness = EleSelected.StrokeThickness / ImgScaleX;

                switch (EleSelected.DrawCommand)
                {
                    case DrawCommand.直线:
                        var new_line = new Line();
                        new_line.Width = cvDrawMain.ActualWidth;
                        new_line.Height = cvDrawMain.ActualHeight;
                        new_line.Stroke = EleSelected.Stroke;
                        new_line.StrokeThickness = thickness;
                        new_line.Fill = EleSelected.Fill;
                        new_line.X1 = EleSelected.LocX;
                        new_line.Y1 = EleSelected.LocY;
                        new_line.X2 = EleSelected.LocX2;
                        new_line.Y2 = EleSelected.LocY2;
                        new_line.DataContext = EleSelected;

                        cvContainer.Children.Add(new_line);
                        drawEleListInUI.Add(EleSelected);
                        BindThicknessScale(new_line, EleSelected);
                        break;
                    case DrawCommand.曲线:
                        var new_curve = new System.Windows.Shapes.Path();
                        new_curve.Width = cvDrawMain.ActualWidth;
                        new_curve.Height = cvDrawMain.ActualHeight;
                        new_curve.Stroke = EleSelected.Stroke;
                        new_curve.StrokeThickness = thickness;
                        new_curve.Fill = EleSelected.FillWidthOpacity;
                        var path = new System.Windows.Shapes.Path();
                        new_curve.Data = Geometry.Parse(EleSelected.CurveDataStr);
                        new_curve.DataContext = EleSelected;

                        cvContainer.Children.Add(new_curve);
                        drawEleListInUI.Add(EleSelected);
                        BindThicknessScale(new_curve, EleSelected);

                        break;
                    case DrawCommand.矩形:
                        var new_rect = new Border();
                        new_rect.BorderBrush = EleSelected.Stroke;
                        new_rect.BorderThickness = new Thickness(thickness);
                        new_rect.Background = EleSelected.FillWidthOpacity;
                        new_rect.Width = EleSelected.SizeWidth;
                        new_rect.Height = EleSelected.SizeHeight;
                        new_rect.CornerRadius = new CornerRadius(EleSelected.BorderRadius);
                        Canvas.SetLeft(new_rect, EleSelected.LocX);
                        Canvas.SetTop(new_rect, EleSelected.LocY);
                        new_rect.DataContext = EleSelected;

                        cvContainer.Children.Add(new_rect);
                        drawEleListInUI.Add(EleSelected);
                        BindThicknessScale(new_rect, EleSelected);
                        break;
                    case DrawCommand.圆形:
                        var new_ell = new Ellipse();
                        new_ell.Stroke = EleSelected.Stroke;
                        new_ell.StrokeThickness = thickness;
                        new_ell.Fill = EleSelected.FillWidthOpacity;
                        new_ell.Width = EleSelected.SizeWidth;
                        new_ell.Height = EleSelected.SizeHeight;
                        Canvas.SetLeft(new_ell, EleSelected.LocX);
                        Canvas.SetTop(new_ell, EleSelected.LocY);
                        new_ell.DataContext = EleSelected;

                        cvContainer.Children.Add(new_ell);
                        drawEleListInUI.Add(EleSelected);
                        BindThicknessScale(new_ell, EleSelected);

                        break;
                    case DrawCommand.文字:
                        var new_text = new TextBlock() { };
                        new_text.Foreground = EleSelected.Stroke;
                        new_text.FontSize = EleSelected.FontSize;
                        new_text.Background = EleSelected.FillWidthOpacity;
                        new_text.Text = EleSelected.TextStr;
                        Canvas.SetLeft(new_text, EleSelected.LocX);
                        Canvas.SetTop(new_text, EleSelected.LocY);
                        new_text.RenderTransformOrigin = new Point(0.5, 0.5);
                        new_text.RenderTransform = gridmain.FindResource("tfg1") as TransformGroup;


                        new_text.MouseMove += New_line_MouseMove;
                        new_text.MouseLeave += New_line_MouseLeave;
                        new_text.MouseDown += Shape_MouseDown;
                        EleSelected.TextStr = "新增文本";
                        cvContainer.Children.Add(new_text);
                        drawEleListInUI.Add(EleSelected);
                        new_text.DataContext = EleSelected;

                        //结束画图
                        curr_draw_going = false;

                        break;
                    case DrawCommand.拖动:
                        break;
                    case DrawCommand.缩放:
                        break;
                    case DrawCommand.复制:
                        break;
                    case DrawCommand.删除:
                        break;
                    default:
                        break;
                }
            });
        }

        private bool ColorSelector(out SolidColorBrush rstbrush)
        {
            rstbrush = Brushes.Black;

            var colorDialog = new System.Windows.Forms.ColorDialog();
            colorDialog.AllowFullOpen = true;
            if (colorDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return false;

            System.Windows.Media.SolidColorBrush scb = new System.Windows.Media.SolidColorBrush();
            System.Windows.Media.Color color = new System.Windows.Media.Color();
            color.A = colorDialog.Color.A;
            color.B = colorDialog.Color.B;
            color.G = colorDialog.Color.G;
            color.R = colorDialog.Color.R;
            scb.Color = color;

            rstbrush = scb;
            return true;

        }

        private void ResetRowHeader()
        {
            if (EleList == null) return;
        }


        private double split_getWidth(int skipCount, int takeCount)
        {
            return split_arr_col.Skip(skipCount).Take(takeCount).Sum();
        }
        private double split_getHeight(int skipCount, int takeCount)
        {
            return split_arr_row.Skip(skipCount).Take(takeCount).Sum();
        }

        private void loadBg()
        {
            try
            {
                if (cvDrawBg == null) return;

                cvDrawBg.Children.Clear();

                split_arr_col = ln_ver_split_arr.Split(',').Select(a => double.Parse(a)).ToArray();
                split_arr_row = ln_hor_split_arr.Split(',').Select(a => double.Parse(a)).ToArray();

                split_arr_sign_col = ln_ver_split_arr_sign.Split(',');
                split_arr_sign_row = ln_hor_split_arr_sign.Split(',');
                var split_arr_sign_row_rev = split_arr_sign_row.Reverse().ToArray();

                if (split_arr_col.Length == 0
                    || split_arr_row.Length == 0) return;


                //边缘长度横纵保持一致
                colWidthItemAvg = split_arr_col.Average();
                rowHeightItemAvg = split_arr_row.Average();
                colWidthItemAvg = (colWidthItemAvg + rowHeightItemAvg) * 0.2;
                rowHeightItemAvg = colWidthItemAvg;


                //var border_ext_lenitem = (split_arr_col.Average() + split_arr_row.Average()) * 0.2;


                //可调整变量
                //总列数
                int colCount = split_arr_col.Length;
                //总行数
                int rowCount = split_arr_row.Length;
                ////列宽
                //var colWidthItem = 200d;
                ////行高
                //var rowHeightItem = 130d;
                //背景线条颜色
                brush_line = new SolidColorBrush(Color.FromRgb(128, 128, 128));
                //背景色
                brush_bg = new SolidColorBrush(Color.FromRgb(33, 40, 48));
                //背景线条宽度 
                //bg_ln_thickness = 3; 
                //4边突出长度 
                var outter_extlen = 50;



                var colCount2 = colCount;
                var rowCount2 = rowCount;
                colCount2 += 4;
                rowCount2 += 4;


                var widthall = split_arr_col.Sum() + colWidthItemAvg * 4;// colWidthItem * colCount2;
                var heightall = split_arr_row.Sum() + rowHeightItemAvg * 4;// rowHeightItem * rowCount2; 
                cvDrawBg.Width = widthall;
                cvDrawBg.Height = heightall;

                //缩放至正好最大看见
                var tflist = cvDrawBg.RenderTransform as TransformGroup;
                var sf1 = tflist.Children[1] as TranslateTransform;



                if (showMeshBg)
                {
                    #region 背景线条
                    //背景线条-横线
                    var x = colWidthItemAvg * 1;
                    var rowMaxCount = rowCount2 - 1 + 1;
                    for (int r = 1; r < rowMaxCount; r++)
                    {
                        var ln = new Line();
                        //ln.StrokeThickness = bg_ln_thickness;
                        ln.DataContext = this;
                        ln.SetBinding(Line.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("bg_ln_thickness"), IsAsync = false });
                        ln.Stroke = brush_line;
                        if (r == 1 || r == rowMaxCount - 1)
                        {
                            ln.X1 = colWidthItemAvg * 2;
                            ln.X2 = widthall - colWidthItemAvg * 2;
                        }
                        else
                        {
                            ln.X1 = x - outter_extlen;
                            ln.X2 = widthall - colWidthItemAvg * 1 + outter_extlen;
                        }
                        if (r < 2) ln.Y1 = r * rowHeightItemAvg;
                        else ln.Y1 = 2 * rowHeightItemAvg + split_arr_row.Take(r - 2).Sum() + Math.Max(0, (r - (rowMaxCount - 2))) * rowHeightItemAvg;
                        ln.Y2 = ln.Y1;

                        cvDrawBg.Children.Add(ln);
                    }
                    //return;

                    var y = rowHeightItemAvg * 1;
                    //背景线条-竖线
                    var colMaxCount = colCount2 - 1 + 1;
                    for (int c = 1; c < colMaxCount; c++)
                    {
                        var ln = new Line();
                        //ln.StrokeThickness = bg_ln_thickness;
                        ln.DataContext = this;
                        ln.SetBinding(Line.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("bg_ln_thickness"), IsAsync = false });
                        ln.Stroke = brush_line;

                        if (c < 2) ln.X1 = c * colWidthItemAvg;
                        else ln.X1 = 2 * colWidthItemAvg + split_arr_col.Take(c - 2).Sum() + Math.Max(0, (c - (colMaxCount - 2))) * colWidthItemAvg;
                        ln.X2 = ln.X1;

                        if (c == 1 || c == colMaxCount - 1)
                        {
                            ln.Y1 = rowHeightItemAvg * 2;
                            ln.Y2 = heightall - rowHeightItemAvg * 2;
                        }
                        else
                        {
                            ln.Y1 = y - outter_extlen;
                            ln.Y2 = heightall - rowHeightItemAvg * 1 + outter_extlen;
                        }

                        cvDrawBg.Children.Add(ln);
                    }
                    //return;
                    //背景方框
                    for (int r = 2; r < rowCount2 - 2 + 1; r++)
                    {
                        for (int c = 2; c < colCount2 - 2 + 1; c++)
                        {
                            //外框
                            var x1 = colWidthItemAvg * 2 + split_getWidth(0, c - 2);// c * colWidthItem;
                            var y1 = rowHeightItemAvg * 2 + split_getHeight(0, r - 2);// r * rowHeightItem;
                            var len_half = colWidthItemAvg * 0.3;
                            x1 -= len_half * 0.5;
                            y1 -= len_half * 0.5;
                            var lenrt = len_half;

                            var ln = new Rectangle();
                            ln.Fill = brush_bg;
                            ln.Width = lenrt;
                            ln.Height = lenrt;
                            Canvas.SetLeft(ln, x1);
                            Canvas.SetTop(ln, y1);
                            cvDrawBg.Children.Add(ln);

                            //内框
                            x1 = colWidthItemAvg * 2 + split_getWidth(0, c - 2);// c * colWidthItem;
                            y1 = rowHeightItemAvg * 2 + split_getHeight(0, r - 2);// r * rowHeightItem;
                            len_half = colWidthItemAvg * 0.15;
                            x1 -= len_half * 0.5;
                            y1 -= len_half * 0.5;
                            lenrt = len_half;

                            ln = new Rectangle();
                            ln.Fill = brush_line;
                            ln.Width = lenrt;
                            ln.Height = lenrt;
                            Canvas.SetLeft(ln, x1);
                            Canvas.SetTop(ln, y1);
                            cvDrawBg.Children.Add(ln);
                        }
                    }
                    #endregion
                }
                //return;
                if (showMeshRule)
                {
                    var ellLen = 100;
                    #region 刻度  序号 - 与方框位置保持一致 
                    var tfg_loc = gridmain.FindResource("tfg1_loc") as TransformGroup;
                    var tfg_yflip_loc = gridmain.FindResource("tfg1_textYFlip_loc") as TransformGroup;
                    var tfg_global_left = FindResource("tfg1") as TransformGroup;
                    var tfg_yflip_global_left = FindResource("tfg1_textYFlip") as TransformGroup;
                    var tfg_global_right = FindResource("tfg2") as TransformGroup;
                    var tfg_yflip_global_right = FindResource("tfg2_textYFlip") as TransformGroup;

                    //序号-上 
                    for (int c = 2; c < colCount2 - 2 + 1; c++)
                    {
                        //外圆圈 
                        var len_half = ellLen * 0.3;
                        var x1 = colWidthItemAvg * 2 + split_getWidth(0, c - 2);// c * colWidthItem;
                        var y1 = rowHeightItemAvg - outter_extlen - len_half * 0.5;// r * rowHeightItem;

                        x1 -= len_half * 0.5;
                        y1 -= len_half * 0.5;
                        var lenrt = len_half;

                        var ln = new Ellipse();
                        //ln.StrokeThickness = bg_ln_thickness;
                        ln.DataContext = this;
                        ln.RenderTransformOrigin = new Point(0.5, 0.5);
                        ln.RenderTransform = tfg_loc;
                        ln.Fill = brush_bg;
                        ln.Stroke = brush_line;
                        ln.Width = lenrt;
                        ln.Height = lenrt;
                        Canvas.SetLeft(ln, x1);
                        Canvas.SetTop(ln, y1);
                        cvDrawBg.Children.Add(ln);

                        //内部文字
                        var txt = new Label();
                        txt.Width = lenrt;
                        txt.Height = lenrt;
                        txt.Content = split_arr_sign_col[c - 2].ToString(); //(c - 1).ToString();
                        txt.FontSize = 16;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                        txt.VerticalContentAlignment = VerticalAlignment.Center;
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_loc;

                        Canvas.SetLeft(txt, x1);
                        Canvas.SetTop(txt, y1);
                        cvDrawBg.Children.Add(txt);

                    }
                    //return;
                    //序号-下
                    for (int c = 2; c < colCount2 - 2 + 1; c++)
                    {
                        //外圆圈 
                        var len_half = ellLen * 0.3;
                        var x1 = colWidthItemAvg * 2 + split_getWidth(0, c - 2);// c * colWidthItem;
                        var y1 = heightall - rowHeightItemAvg + outter_extlen + len_half * 0.5;

                        x1 -= len_half * 0.5;
                        y1 -= len_half * 0.5;
                        var lenrt = len_half;

                        var ln = new Ellipse();
                        //ln.StrokeThickness = bg_ln_thickness;
                        ln.DataContext = this;
                        ln.RenderTransformOrigin = new Point(0.5, 0.5);
                        ln.RenderTransform = tfg_loc;
                        ln.Fill = brush_bg;
                        ln.Stroke = brush_line;
                        ln.Width = lenrt;
                        ln.Height = lenrt;
                        Canvas.SetLeft(ln, x1);
                        Canvas.SetTop(ln, y1);
                        cvDrawBg.Children.Add(ln);

                        //内部文字
                        var txt = new Label();
                        txt.Width = lenrt;
                        txt.Height = lenrt;
                        txt.Content = split_arr_sign_col[c - 2].ToString();
                        txt.FontSize = 16;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                        txt.VerticalContentAlignment = VerticalAlignment.Center;
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_loc;
                        Canvas.SetLeft(txt, x1);
                        Canvas.SetTop(txt, y1);
                        cvDrawBg.Children.Add(txt);

                    }
                    //return;
                    //序号-左侧  
                    var maxno = rowCount2 - 2 + 1;
                    for (int r = 2; r < maxno; r++)
                    {
                        //外圆圈 
                        var len_half = ellLen * 0.3;
                        var x1 = colWidthItemAvg - outter_extlen - len_half * 0.5;
                        var y1 = rowHeightItemAvg * 2 + split_getHeight(0, r - 2);

                        x1 -= len_half * 0.5;
                        y1 -= len_half * 0.5;
                        var lenrt = len_half;

                        var ln = new Ellipse();
                        ln.DataContext = this;
                        ln.RenderTransformOrigin = new Point(0.5, 0.5);
                        ln.RenderTransform = tfg_global_left;
                        ln.Fill = brush_bg;
                        ln.Stroke = brush_line;
                        ln.Width = lenrt;
                        ln.Height = lenrt;
                        Canvas.SetLeft(ln, x1);
                        Canvas.SetTop(ln, y1);
                        cvDrawBg.Children.Add(ln);

                        //内部文字
                        var txt = new Label();
                        txt.Width = lenrt;
                        txt.Height = lenrt;
                        txt.Content = split_arr_sign_row_rev[r - 2].ToString();
                        txt.FontSize = 16;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                        txt.VerticalContentAlignment = VerticalAlignment.Center;
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_loc;
                        Canvas.SetLeft(txt, x1);
                        Canvas.SetTop(txt, y1);
                        cvDrawBg.Children.Add(txt);
                    }
                    //return;
                    //序号-右侧  
                    maxno = rowCount2 - 2 + 1;
                    for (int r = 2; r < maxno; r++)
                    {
                        //外圆圈 
                        var len_half = ellLen * 0.3;
                        var x1 = widthall - colWidthItemAvg + outter_extlen + len_half * 0.5;
                        var y1 = rowHeightItemAvg * 2 + split_getHeight(0, r - 2); ; // r * rowHeightItem;

                        x1 -= len_half * 0.5;
                        y1 -= len_half * 0.5;
                        var lenrt = len_half;

                        var ln = new Ellipse();
                        //ln.StrokeThickness = bg_ln_thickness; 
                        ln.DataContext = this;
                        ln.RenderTransformOrigin = new Point(0.5, 0.5);
                        ln.RenderTransform = tfg_global_right;
                        ln.Fill = brush_bg;
                        ln.Stroke = brush_line;
                        ln.Width = lenrt;
                        ln.Height = lenrt;
                        Canvas.SetLeft(ln, x1);
                        Canvas.SetTop(ln, y1);
                        cvDrawBg.Children.Add(ln);

                        //内部文字
                        var txt = new Label();
                        txt.Width = lenrt;
                        txt.Height = lenrt;
                        txt.Content = split_arr_sign_row_rev[r - 2].ToString();
                        txt.FontSize = 16;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                        txt.VerticalContentAlignment = VerticalAlignment.Center;
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_loc;
                        Canvas.SetLeft(txt, x1);
                        Canvas.SetTop(txt, y1);
                        cvDrawBg.Children.Add(txt);
                    }
                    //return;
                    //刻度单位说明-上 *******************************
                    for (int c = 2; c < colCount2 - 2; c++)
                    {
                        // 文字
                        var txt = new Label();
                        txt.Width = split_getWidth(c - 2, 1);// colWidthItemAvg;
                        txt.Content = ((int)split_getWidth(c - 2, 1)).ToString();
                        txt.FontSize = 12;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                        txt.VerticalContentAlignment = VerticalAlignment.Bottom;
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_loc;
                        Canvas.SetLeft(txt, colWidthItemAvg * 2 + split_getWidth(0, c - 2));
                        Canvas.SetTop(txt, rowHeightItemAvg - 50);
                        cvDrawBg.Children.Add(txt);

                    }
                    //
                    //刻度单位说明-下 
                    for (int c = 2; c < colCount2 - 2; c++)
                    {
                        // 文字
                        var txt = new Label();
                        txt.Width = split_getWidth(c - 2, 1);
                        txt.Content = ((int)split_getWidth(c - 2, 1)).ToString();
                        txt.FontSize = 12;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                        txt.VerticalContentAlignment = VerticalAlignment.Top;
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_loc;
                        Canvas.SetLeft(txt, colWidthItemAvg * 2 + split_getWidth(0, c - 2));
                        Canvas.SetTop(txt, heightall - rowHeightItemAvg + 10);
                        cvDrawBg.Children.Add(txt);

                    }
                    //return;
                    //刻度单位说明-左侧  
                    for (int r = 2; r < rowCount2 - 2; r++)
                    {
                        // 文字
                        var txt = new Label();
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_global_left;
                        txt.Height = split_getHeight(r - 2, 1);
                        txt.Content = ((int)split_getHeight(r - 2, 1)).ToString();
                        txt.FontSize = 12;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Right;
                        txt.VerticalContentAlignment = VerticalAlignment.Center;
                        Canvas.SetLeft(txt, colWidthItemAvg - 60);
                        Canvas.SetTop(txt, rowHeightItemAvg * 2 + split_getHeight(0, r - 2));
                        cvDrawBg.Children.Add(txt);

                    }
                    //刻度单位说明-右侧  
                    for (int r = 2; r < rowCount2 - 2; r++)
                    {
                        // 文字
                        var txt = new Label();
                        txt.RenderTransformOrigin = new Point(0.5, 0.5);
                        txt.RenderTransform = tfg_yflip_global_right;
                        txt.Height = split_getHeight(r - 2, 1);
                        txt.Content = ((int)split_getHeight(r - 2, 1)).ToString();
                        txt.FontSize = 12;
                        txt.Foreground = Brushes.White;
                        txt.HorizontalContentAlignment = HorizontalAlignment.Left;
                        txt.VerticalContentAlignment = VerticalAlignment.Center;
                        Canvas.SetLeft(txt, widthall - colWidthItemAvg + 00);
                        Canvas.SetTop(txt, rowHeightItemAvg * 2 + split_getHeight(0, r - 2));
                        cvDrawBg.Children.Add(txt);
                    }
                    #endregion

                }
            }
            catch (Exception)
            {

            }
        }

        internal void ClearDrawList()
        {
            cvDrawMain.Children.Clear();
            drawEleListInUI.Clear();
            lst_container_jiedian.Clear();
            lst_searched_jiedian.Clear();
            lst_searched_jiedian_novalid.Clear();

        }


        #endregion



        public event PropertyChangedEventHandler PropertyChanged;
        public void cc(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }


    }
    public class CanvasExt : Canvas
    {
        public HKP_TakeoffDto Data_Jiedian { get; internal set; }
    }
}
